package com.demo.rbactest.handle;

import com.demo.rbactest.utils.TokenTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器,需要携带token才能访问
 */
@Slf4j
@Component
public class TokenHandel implements HandlerInterceptor {

    //    要放行的url
    private final String[] urls = new String[]{"/login", "/register"};


    //    进入controller层之前拦截请求
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        获取请求的uri
        final String uri = request.getRequestURI();
//        获取携带的token
        final String token = request.getHeader("token");
//        获取请求方法
        final String method = request.getMethod();
        // 判断不是跨域请求
        if (!method.equals("OPTIONS")) {
            //        遍历不拦截的url,放行
            for (String url : urls) {
                if (url.equals(uri)) {
                    return true;
                }
            }

//        验证token,成功后放行
            if (TokenTool.parse(token)) {
                return true;
            } else {
                throw new RuntimeException("token验证失败,你没有权限");
            }
        }

        return false;
    }

}
